package belf.migrate.engine.job.structure.helper;

import belf.migrate.api.exception.CatalogException;
import belf.migrate.api.table.schema.Catalog;
import belf.migrate.api.table.schema.TablePath;
import belf.migrate.api.taskconf.JobContext;
import belf.migrate.api.taskconf.Task;
import belf.migrate.api.type.DbObjectType;
import belf.migrate.api.type.LogLevelType;
import belf.migrate.api.util.ExceptionUtils;
import belf.migrate.api.util.PostLog;
import belf.migrate.api.job.Job;
import belf.migrate.engine.job.JobResult;
import belf.migrate.engine.job.JobResultItem;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.util.Date;
import java.util.List;

import static belf.migrate.api.job.JobCode.*;

@Slf4j
public class DropProcedureTool extends NonTableTool {
    public DropProcedureTool(Job job) {
        super(job);
    }

    public DropProcedureTool(Job job, JobContext jobContext) {
        super(job, jobContext);
    }

    @Override
    public JobResult run() {
        PostLog.sendLogModel(
                job.getJobId(),
                job.getTask().getTaskType().getName(),
                "删除存储过程开始！",
                LogLevelType.INFO.getType(),
                EXECUTING,
                jobContext.getProgress());
        JobResult jobResult = new JobResult(SUCCESS, "删除选中的存储过程成功");
        Catalog sinkCatalog = jobContext.getSinkCatalog();

        try {
            List<String> procNames = job.getMissions(); //用户是否指定了要创建的存储过程的名字？
            if (procNames == null || procNames.isEmpty()) {
                procNames = sinkCatalog.listProcedureNames(jobContext.getTaskConf().getSinkConf().getDatabaseName(),
                        jobContext.getTaskConf().getSinkConf().getSchemaName());
            }

            if (null != procNames) {
                for (String procName : procNames) {
                    jobContext.addProgress(DbObjectType.PROCEDURE.getTypeName(), procNames.size());
                    JobResultItem jobResultItem = process(procName, sinkCatalog);
                    jobResult.addItem(jobResultItem);
                    if (jobResultItem.getCode() != SUCCESS
                            && job.getTask().getTaskPolicy() == Task.TaskPolicy.ERROR_STOP) {
                        break;  //遇到错误即返回
                    }
                }
            }
        } catch (CatalogException e) {
            e.printStackTrace();
        }

        if (jobResult.getFailtures() > 0) {
            jobResult.setCode(DROP_PROCEDURE_ERROR);
            jobResult.setMessage("删除选中的存储过程失败");
            log.error("Drop Some Procedures Of {} Failed.", jobContext.getValidSinkDatabase());
        } else {
            log.info("Drop All Procedures Of {} Successfully.", jobContext.getValidSinkDatabase());
        }

        PostLog.sendLogModel(
                job.getJobId(),
                job.getTask().getTaskType().getName(),
                "删除存储过程结束！",
                LogLevelType.INFO.getType(),
                EXECUTING,
                jobContext.getProgress());
        return jobResult;

    }

    public JobResultItem process(String procName, Catalog sinkCatalog) {
        String startTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        TablePath targetPath = TablePath.of(jobContext.getTaskConf().getSinkConf().getDatabaseName(),
                jobContext.getTaskConf().getSinkConf().getSchemaName(),
                procName,
                getSinkQualifiersModel());
        try {
            sinkCatalog.dropProcedure(targetPath);
        } catch (Exception e) {
            e.printStackTrace();
            PostLog.sendLogModel(
                    job.getJobId(),
                    job.getTask().getTaskType().getName(),
                    "目标库" + "删除存储过程失败：" + e.getMessage(),
                    LogLevelType.ERROR.getType(),
                    EXECUTING,
                    jobContext.getProgress());
            String endTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
            return new JobResultItem(procName,
                    targetPath.getCaseTableName(),
                    DROP_PROCEDURE_ERROR,
                    "目标库" + "删除存储过程失败：" + e.getMessage(),
                    ExceptionUtils.toString(e.getCause()),
                    DbObjectType.PROCEDURE.getTypeName(),
                    startTime,
                    endTime,
                    null,
                    sinkCatalog.getDropProcedureSql(targetPath));
        }
        PostLog.sendLogModel(
                job.getJobId(),
                job.getTask().getTaskType().getName(),
                "删除存储过程" + procName + "成功",
                LogLevelType.ERROR.getType(),
                EXECUTING,
                jobContext.getProgress());
        JobResultItem jobResultItem = new JobResultItem(
                procName,
                targetPath.getCaseTableName(),
                SUCCESS,
                "删除存储过程" + procName + "成功");
        jobResultItem.setSinkDdl(sinkCatalog.getDropProcedureSql(targetPath));
        jobResultItem.setStartTime(startTime);
        String endTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        jobResultItem.setEndTime(endTime);
        jobResultItem.setType(DbObjectType.PROCEDURE.getTypeName());
        return jobResultItem;
    }
}
